import React, { useState, useEffect, useCallback } from 'react'
import { Col, Form, Input, Button, Select, Table, Modal, Row } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { getSupplierList, getStoreListById, getSNcode, savePOS, authAboutWeChat, bindWeChat, lookBindRecord, getPOSInfoById, getPrintInfoById } from '@/services/supplier/store/addPOS'

const { Option } = Select
// 交易信息设置表头
const columns = [
  {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center'
  },
  {
      title: '清算同道',
      dataIndex: 'way',
      key: 'way',
      align: 'center'
  },
  {
      title: 'POS商户号',
      dataIndex: 'supplierId',
      key: 'supplierId',
      align: 'center'
  },
  {
      title: 'POS终端号',
      dataIndex: 'terminalId',
      key: 'terminalId',
      align: 'center',
  },
  {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center'
  },
  {
      title: '更新时间',
      dataIndex: 'changeTime',
      key: 'changeTime',
      align: 'center'
  }
]
// 小程序绑定记录表头
const recordColumns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center'
  }
]
// 清算信息配置表头
const clearColumns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center'
  },
  {
    title: '支付类型',
    dataIndex: 'payWay',
    key: 'payWay',
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center'
  },
  {
      title: '更新时间',
      dataIndex: 'changeTime',
      key: 'changeTime',
      align: 'center'
  }
]
// 打印信息配置表头
const printColumns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center'
  },
  {
    title: '支付类型',
    dataIndex: 'payWay',
    key: 'payWay',
    align: 'center'
  },
  {
    title: '打印联',
    dataIndex: 'PrintAl',
    key: 'PrintAl',
    align: 'center'
  },
  {
    title: '打印间隔',
    dataIndex: 'printInterval',
    key: 'printInterval',
    align: 'center'
  },
  {
    title: '打印模板',
    dataIndex: 'model',
    key: 'model',
    align: 'center'
  }
]

const AddPOS = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [supplierList, setSupplierList] = useState([])
  const [storeList, setStoreList] = useState([])
  const [SNcode, setSNcode] = useState('')
  const [storeTypeList, setStoreTypeList] = useState([
    {
      id: 'ONLINE',
      name: '线上'
    },
    {
      id: 'OFFLINE',
      name: '线下'
    }
  ])
  const [tradeList, setTradeList] = useState([]) // 交易信息列表
  const [visible, setVisible] = useState(false)
  const [bindRecordList, setBindRecordList] = useState([])
  const [recordVisible, setRecordVisible] = useState(false)
  const [clearList, setClearList] = useState([])
  const [printList, setPrintList] = useState([])
  const [POSInfo, setPOSInfo] = useState({})

  useEffect(() => {
    judgePageType()
    init()
  }, [])

  const init = async () => {
    await getSupplierLists()
  }
  // 判断页面类型 (新增POS/修改POS
  const judgePageType = () => {
    const { location } = props
    if (location.query.POSId) {
      console.log('set')
      getPOSInfoByIds(location.query.POSId)
    } else {
      console.log('add')
    }
  }
  // 根据POS机id获取POS信息
  const getPOSInfoByIds = async (id) => {
    let params = {
      id
    }
    let res =  await getPOSInfoById(params)
    if (res.code === '0') {
      setPOSInfo(res.data)
      form.validateFields((err, values) => {
        values.supplierId = res.data.id
        console.log('Received values of form: ', values)
      })

    } else {
      alert(res.msg)
    }
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)

    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <Col span={8}>
        <Form.Item label={`名称`}>
          {getFieldDecorator(`id`, {})
            (<Input />)}
        </Form.Item>
      </Col>
    )
  }
  // 按钮处理
  const handleBtn = async type => {
    switch (type) {
      case 3:
        await savePOSs()
        break
    }
  }
  // 返回按钮
  const goBack = () => {
    props.history.goBack(-1)
  }
  // 基本信息模块
  const BaseInfoView = useCallback(() => {
    return(<>
      <Row style={{color: '#0b89d4', borderBottom: '1px solid #ddd', padding: '12px', background: '#fff', marginTop: '12px'}}>基本信息</Row>
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`所属商户`}>
              {getFieldDecorator(`supplierId`, {})
                (<Select
                  style={{ width: '100%' }}
                  showSearch
                  filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                  placeholder="请选择"
                  onChange={selectSupplier}
                >
                  { supplierList && supplierList.map(r => <Option key={r.id} value={r.id}>{r.merchantName}</Option>)}
                </Select>)
              }
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`所属门店`}>
              {getFieldDecorator(`storeId`, {})
                (<Select
                  style={{ width: '100%' }}
                  showSearch
                  filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                  placeholder="请选择"
                >
                  { storeList && storeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
                </Select>)
              }
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`开户银行`}>
              {getFieldDecorator(`collectionOpen`, {})
                (<Input placeholder="请输入开户银行" />)}
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`POS名称`}>
              {getFieldDecorator(`posName`, {})
                (<Input placeholder="POS名称" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`POS编号/SN`}>
              {getFieldDecorator(`sn`, {})
                (<>
                  <Input placeholder="POS编号/SN" value={SNcode} style={{width: '50%'}} />
                  <Button type="primary" onClick={() => getSNcodes()} style={{marginLeft: '24px'}}>自动生成</Button>
                </>)
                }
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`交易终端号`}>
              {getFieldDecorator(`collectionNumber`, {})
                (<Input placeholder="请输入交易终端号" />)}
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`交易商户号`}>
              {getFieldDecorator(`collectionSupplier`, {})
                (<Input placeholder="请输入交易商户号" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
        <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`门店类型`}>
            {getFieldDecorator(`posType`, {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { storeTypeList && storeTypeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)
              }
        </Form.Item>
      </Col>
      </Row>
      </>
    )
  }, [supplierList, storeList, SNcode])
  // 获取全部商户
  const getSupplierLists = async () => {
    let res = await getSupplierList()
    if (res.code === '0') {
      setSupplierList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 选择商户
  const selectSupplier = async (value) => {
    await getStoreListByIds(value)
  }
  // 根据商户ID获取门店列表
  const getStoreListByIds = async (id) => {
    let params = {
      supplierId: id
    }
    let res = await getStoreListById(params)
    if (res.code === '0') {
      setStoreList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 获取POS编号
  const getSNcodes = async () => {
    let res = await getSNcode()
    setSNcode(res)
  }
  // 保存信息
  const savePOSs = async () => {
    let obj
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      obj = values
    })
    let params = {
      collectionOpen: obj.collectionOpen, // 开户银行
      sn: SNcode, // POS编号/SN
      collectionNumber: obj.collectionNumber, // 交易终端号
      collectionSupplier: obj.collectionSupplier, // 交易商户号
      posType: obj.posType, // ONLINE
      netType: '',
      certPath: '',
      ip: '',
      tpduValue: '',
      port: '',
      posSerialNo: '',
      posSupplier: '',
      baudRate: '',
      posSign: '',
      supplierId: obj.supplierId, // 商户ID
      storeId: obj.storeId, // 店铺ID
      posName: obj.posName // POS名称
    }
    let res = await savePOS(params)
    alert(res.msg)
  }
  // 交易信息设置模块
  const TradeInfoView = () => {
    return (
      <>
        <Row style={{color: '#0b89d4', borderBottom: '1px solid #ddd', padding: '12px', background: '#fff', marginTop: '12px'}}>交易信息设置</Row>
        <Table
          columns={columns}
          dataSource={tradeList}
          rowKey={record => record.id}
        />
      </>
    )
  }
  // 小程序绑定支付
  const PayByWeChatView = () => {
    return (
      <>
        <Row style={{color: '#0b89d4', borderBottom: '1px solid #ddd', padding: '12px', background: '#fff', marginTop: '12px'}}>小程序绑定支付</Row>
        <Button type="primary" onClick={authAboutWeChats} style={{margin: '12px 24px 12px 0'}}>绑定设置</Button>
        <Button type="danger" onClick={lookBindRecords} style={{margin: '12px 24px 12px 0'}}>>绑定记录</Button>
        <Table />
        <Modal
          title="小程序绑定支付"
          visible={visible}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Form.Item label={`商户号`}>
              {getFieldDecorator(`supplierCode`, {})
                (<Input placeholder="请输入商户号" />)}
          </Form.Item>
          <Form.Item label={`appid`}>
              {getFieldDecorator(`appid`, {})
                (<Input placeholder="请输入appid" />)}
          </Form.Item>
        </Modal>

        <Modal
          title="小程序绑定记录"
          visible={recordVisible}
          onOk={recordHandleOk}
          onCancel={recordHandleCancel}
        >
          <Table
            columns={recordColumns}
            dataSource={bindRecordList}
            rowKey={record => record.id}
          />
        </Modal>
      </>
    )
  }
  const showModal = () => {
    setVisible(true)
  }

  const handleOk = e => {
    bindWeChats()
    setVisible(false)
  }
  // 绑定小程序
  const bindWeChats = async () => {
    let obj
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      obj = values
    })
    let params = {
      merchantsNo: obj.supplierId
    }
    let res = await bindWeChat()
    if (res.code === '0') {

    } else {
      alert(res.msg)
    }
  }

  const handleCancel = e => {
    console.log(e)
    setVisible(false)
  }
  // 绑定小程序
  const authAboutWeChats = async () => {
    // 检查是否有绑定小程序的权限
    let obj
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      obj = values
    })
    if (!obj.supplierId) {
      alert('请选择所属商户和所属门店!')
      return
    }
    let params = {
      bindingType: 1,
      supplierId: obj.supplierId
    }
    let res = await authAboutWeChat(params)
    if (res.code === '0') {
      showModal()
    } else {
      alert(res.msg)
    }
  }
  // 查看小程序绑定记录
  const lookBindRecords = async () => {
    let obj
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      obj = values
    })

    if (!obj.storeId) {
      alert('请选择所属商户和所属门店!')
      return
    }
    let params = {
      pageNo: 1,
      pageSize: 9999,
      storeId: obj.storeId
    }
    let res = await lookBindRecord(params)
    if (res.code === '0') {
      setBindRecordList(res.data)
      recordShowModal()
    } else {
      alert(res.msg)
    }
  }
  const recordShowModal = () => {
    setRecordVisible(true)
  }

  const recordHandleOk = e => {
    console.log(e)
    setRecordVisible(false)
  }

  const recordHandleCancel = e => {
    console.log(e)
    setRecordVisible(false)
  }
  // 清算信息配置
  const ClearInfoView = () => {
    return (<>
      <Row style={{color: '#0b89d4', borderBottom: '1px solid #ddd', padding: '12px', background: '#fff', marginTop: '12px'}}>清算信息配置</Row>
        <Table
          columns={clearColumns}
          dataSource={clearList}
          rowKey={record => record.id}
        />
    </>)
  }
  // 打印信息配置
  const PrintInfoView = () => {
    return (<>
      <Row style={{color: '#0b89d4', borderBottom: '1px solid #ddd', padding: '12px', background: '#fff', marginTop: '12px'}}>打印信息配置</Row>
        <Table
          columns={printColumns}
          dataSource={printList}
          rowKey={record => record.id}
        />
    </>)
  }

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Button type="primary" onClick={goBack}>返回</Button>
      <BaseInfoView />
      <TradeInfoView />
      <ClearInfoView />
      <PayByWeChatView />
      <PrintInfoView />
   </PageHeaderWrapper>
  )
}

export default Form.create()(AddPOS)
